import sys
import os

from http import HTTPStatus

thisDir = os.path.split(os.path.realpath(__file__))[0]
sys.path.append(os.path.join(thisDir, ".."))
sys.path.append(os.path.join(thisDir, "..", "ps"))
sys.path.append(os.path.join(thisDir, "..", "..", "common"))

import SessionManager
import EJOConst
import EJOHandlerHelper

from EJOHandlerBase import EJOHandlerBase

import logging
logger = logging.getLogger(__name__)

class EJOFinanceEventExpenseProvider(EJOHandlerHelper.EJOAmountWithCurrencyProvider):
    def __init__(self, eventId):
        self.__eventId = eventId

    def Get(self):
        sql = f"select bill.Amount as amount, bill.Datetime as datetime, bill.Currency as currency from bill where ID in (select Bill from mapbillfinanceevent where Event={self.__eventId})"
        db = SessionManager.SessionManager().GetProperty(EJOConst.SESSION_PROPERTY_DB)
        for row in db.Execute(sql):
            # amount, date, currency
            yield row[0], row[1], row[2]

class EJOGetFinanceEvent(EJOHandlerBase):
    def _doHandle(self):
        logger.debug(f"Handled by: {__name__}")

        eventName = self._getParamValue("name")
        session = self._getParamValue("session")

        fid = SessionManager.SessionManager().GetProperty(EJOConst.SESSION_PROPERTY_FAMILY_ID, session)

        eventFilter = " and financeevent.Name like '%" + eventName + "%'" if eventName != "" else ""
        sql = "select " + \
             "financeevent.ID as id, " + \
             "financeevent.Name as name, " + \
             "financeevent.Budget as budget, " + \
             "financeevent.Note as note " + \
             "from financeevent " + \
             "where FID=" + str(fid) + \
             eventFilter + \
             " order by financeevent.Name asc"

        db = SessionManager.SessionManager().GetProperty(EJOConst.SESSION_PROPERTY_DB)
        result = []
        for row in db.Execute(sql):
            # Sqlite supports reentrancy? Yes!
            eventId = row[0]
            name = row[1]
            budget = row[2]
            note = row[3]
            expences = EJOHandlerHelper.EJOSumByCurrency(EJOFinanceEventExpenseProvider(eventId).Get())
            balance = round(budget - expences, 2)
            result.append([name, budget, balance, note])

        return True, HTTPStatus.OK, str(result)

